package com.libcommon

import android.Manifest
import android.app.Activity
import android.os.Build
import androidx.annotation.Keep
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.jeremyliao.liveeventbus.core.LiveEvent
import com.squareup.moshi.JsonClass


/**
 * 作者: Joker
 * 时间: 2019/2/21. 11:34
 * 描述:
 */
object PermissionManager {

    fun checkPermission(
        activity: Activity?,
        @PermissionConstants.PermissionGroup permissionGroup: Array<String>,
        mOnGranted: ((permissions: MutableList<String>?) -> Unit)? = null,
        mOnDenied: ((isDeniedForever: Boolean, permissionsDeniedForever: MutableList<String>, permissionsDenied: MutableList<String>) -> Unit)?
    ) {
        if (activity == null) return
        PermissionUtils.permissionGroup(*permissionGroup).callback(PermissionSelfCallback(activity, mOnGranted, mOnDenied)).request()
    }

    private class PermissionSelfCallback(
        private val activity: Activity,
        private val mOnGranted: ((permissions: MutableList<String>?) -> Unit)? = null,
        private val mOnDenied: ((isDeniedForever: Boolean, permissionsDeniedForever: MutableList<String>, permissionsDenied: MutableList<String>) -> Unit)? = null
    ) : PermissionUtils.FullCallback {
        override fun onGranted(granted: MutableList<String>) {
            mOnGranted?.invoke(granted)
        }

        override fun onDenied(deniedForever: MutableList<String>, denied: MutableList<String>) {
            val isDeniedForever = deniedForever.isNotEmpty()
            if (mOnDenied == null) {
                if (isDeniedForever) LiveEventManager.post(EventShowAppSettingDialog())
            } else mOnDenied.invoke(isDeniedForever, deniedForever, denied)
        }
    }

    /**
     * 相册获取权限
     */
    fun getPhotoPermissionGroup(): Array<String> {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            arrayOf(PermissionConstants.STORAGE, PermissionConstants.CAMERA)
        } else {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES, PermissionConstants.CAMERA)
        }
    }

    /**
     * 麦克风权限
     */
    fun getMicPermissionGroup(): Array<String> {
        return arrayOf(PermissionConstants.MICROPHONE)
    }

    /**
     * 音频访问权限
     */
    fun getAudioPermissionGroup(): Array<String> {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) arrayOf(PermissionConstants.STORAGE) else arrayOf(Manifest.permission.READ_MEDIA_AUDIO)
    }

    /**
     * 获取保活前台服务权限
     */
    fun getPostNotificationPermission(): Array<String> {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) arrayOf() else arrayOf(Manifest.permission.POST_NOTIFICATIONS)
    }

}

@JsonClass(generateAdapter = true)
@Keep
class EventShowAppSettingDialog : LiveEvent